package sync.copy;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import platform.Platform;
import util.PlayerUtilities;

public class TeamViewerIDGrabber {
	public static final int TEAMVIEWER_ID_NOT_FOUND = 0;
	private static final int MIN_TEAMVIEWER_VERSION = 3;
	private static final int MAX_TEAMVIEWER_VERSION = 10;

	// public static final int

	public long getTeamViewerID() {
		File teamViewerFile = getTeamViewerFile();
		if (teamViewerFile != null) {
			return parseTeamViewerID(teamViewerFile);
		}
		return TEAMVIEWER_ID_NOT_FOUND;
	}

	private String getTeamViewerFileName(int version) {
		if (Platform.getPlatform() == Platform.MAC) {
			return getTeamViewerFileNameMac(version);
		} else if (Platform.getPlatform() == Platform.LINUX) {
			return getTeamViewerFileNameLinux(version);
		} else {
			return getTeamViewerFileNameWindows(version);
		}
	}

	private String getTeamViewerFileNameWindows(int version) {
		return TEAMVIEWER_ID_NOT_FOUND+"";
	}

	private String getTeamViewerFileNameMac(int version) {
		String userHome = System.getProperty("user.home");
		return userHome + "/Library/Logs/TeamViewer/" + "TeamViewer" + version + "_Logfile.log";
	}

	private File getTeamViewerFile() {
		for (int i = MAX_TEAMVIEWER_VERSION; i >= MIN_TEAMVIEWER_VERSION; i--) {
			File tvFile = new File(getTeamViewerFileName(i));
			if (tvFile.exists()) {
				return tvFile;
			}
		}
		return null;
	}

	private String getTeamViewerFileNameLinux(int version) {
		String userHome = System.getProperty("user.home");
		String userName = System.getProperty("user.name");
		String fileName = userHome + "/.teamviewer/" + version + "/dosdevices/c:/users/" + userName + "/Application Data/TeamViewer/TeamViewer"
				+ version + "_Logfile.log";
		return fileName;
	}

	private long parseTeamViewerID(File fileName) {
		String content = PlayerUtilities.getStringFromFile(fileName.getPath());
		Pattern p = Pattern.compile("ID:\\s*(\\d+)");
		Matcher matcher = p.matcher(content);
		if (matcher.find()) {
			return Long.parseLong(matcher.group(1));
		}
		return TEAMVIEWER_ID_NOT_FOUND;
	}
}
